from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.settings import api_settings

from oauth.exceptions import OAuthQQAPIError
from oauth.models import OAuthQQUser
from oauth.utils import OAuthQQ
from oauth.serializers import OAuthQQUserSerializer


class OAuthQQURLView(APIView):
    """
    提供QQ登录的网址的接口
    """
    def get(self,request):
        '''获取QQ登录的url'''
        next = request.query_params.get('next','/')

        oauth_qq = OAuthQQ(state=next)

        login_url = oauth_qq.get_qq_login_url()
        return Response({"login_url":login_url})


class QQAuthUserView(CreateAPIView):
    '''qq用户登录'''

    serializer_class = OAuthQQUserSerializer

    def get(self,request):
        code = request.query_params.get("code")
        if not code:
            return Response({'message':"缺少code"},status=status.HTTP_400_BAD_REQUEST)

        oauth = OAuthQQ()

        try:
            access_token = oauth.get_access_token(code)
            # print('xxxxxxxxxxxxxxxxxxxxxxxxxx',access_token)
            openid =oauth.get_openid(access_token)
            # print('oooooooooo',openid)
        except OAuthQQAPIError:
            return Response({'message':'QQ服务异常'},status=status.HTTP_503_SERVICE_UNAVAILABLE)

        # 根据openid查询数据库OAuthQQUser  判断数据是否存在
        try:
            oauth_qq_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            #  第一次用QQ登录 如果数据不存在，处理openid 并返回
            access_token = oauth.generate_bind_user_access_token(openid)
            return Response({'access_token':access_token})
        else:
            # 如果数据存在，表示用户已经绑定过身份， 签发JWT token
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            user = oauth_qq_user.user
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            return Response({
                'username':user.username,
                'user_id':user.id,
                'token':token
            })

    # 因为是同一个路由，可以把post请求放在一起，继承父类省略代码
    # QQ没有绑定用户时第一次绑定会发post 请求
